package com.cheng.tetris;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;


//本类为处理重复发出的键盘事件，重复发出的事件只会调用一次对应方法
public abstract class KeyHandler
        extends KeyAdapter
{

    //放置每一个按键对应的信号的map
    private Map<Integer, KeyEvent> signals;

    //调用那个一直需要被调用的线程
    Thread thread;
    protected KeyHandler()
    {
        super();
        signals = new LinkedHashMap<>();
        thread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    Collection<KeyEvent> values = signals.values();
                    if (values != null)
                    {
                        for (KeyEvent e : values)
                        {
                            if (e != null)
                            {
                                alwaysRepetitiveKePressed(e);
                            }
                        }
                    }
                    try
                    {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        super.keyPressed(e);

        repetitiveKeyPressed(e);//无论什么时候都调用不消除重复的回调

        //当第一次的时候将对应按键的信号设置为对应的event，且如果信号为null就不再执行了
        if(signals.get(e.getKeyCode()) != null) return;
        else
        {
            signals.put(e.getKeyCode(), e);
        }
        noneRepetitiveKeyPressed(e);
    }

    @Override
    public void keyReleased(KeyEvent e)
    {
        super.keyReleased(e);

        newKeyReleased(e);
        //当按键抬起来后，设置信号为null
        signals.put(e.getKeyCode(), null);
    }

    //不会重复的回调
    public void noneRepetitiveKeyPressed(KeyEvent e){}

    //原来功能的回调（为让用户不去用原来的回调忘记用super产生冲突）
    public void repetitiveKeyPressed(KeyEvent e){}

    public void newKeyReleased(KeyEvent e){}

    //从按下就一直被调用的函数
    public void alwaysRepetitiveKePressed(KeyEvent e){}
}
